package web.dynamic.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;

public class DCM /* Dynamic Component Manager */{

	public static void init() {

		defCache = new HashMap<String, DynDef>();
		typeCache = new HashMap<String, DynType>();
		
		List<DynModelProp> props = new ArrayList<DynModelProp>();
		DynModelProp p = new DynModelProp();
		p.setName("Name");
		p.setType("text");
		props.add(p);
		p = new DynModelProp();
		p.setName("OrderCount");
		p.setType("integer");
		props.add(p);
		p = new DynModelProp();
		p.setName("LastOrderDate");
		p.setType("datetime");
		props.add(p);
		
		
		DynDef dynModel = new DynDef();
		dynModel.setType("dynmodel");
		dynModel.put("properties", props);
		
		DynDef dynStore = new DynDef();
		dynStore.setType("dynstore");
		dynStore.put("model", dynModel.values());
		
		DynDef dynForm = new DynDef();
		dynForm.setName("example.sales.saleinfo.form");
		dynForm.setType("dynform");
		dynForm.put("store", dynStore);
		dynForm.put("fields", dynModel.get("properties"));

		defCache.put("example.sales.saleinfo.form", dynForm);
		
		
		typeCache.put("dynform", new DynForm());
		

	}

	public static HashMap<String, DynDef> defCache; /*dynamic definition cache */
	public static HashMap<String, DynType> typeCache; /* type registry */ 

	public static <T> T createComponent(String fqn) {
		if (defCache.containsKey(fqn)) {
			return DCM.<T> create(defCache.get(fqn));
		} else {
			// TODO: load components from server
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private static <T> T create(DynDef def) {
		return (T)typeCache.get(def.getType()).create(def);
	}
	
	// TODO: convert to factory, factory creates mappers, these mappers essentially must populate there required properties,
	// seems like its gonna have to be a lot of hardcoding :(, but might be able to move it to the db :).
	@SuppressWarnings("unchecked")
	public static Field createField( String type ){
		if( type == "text" ){
			return new TextField<String>();
		}else if( type == "integer" ){
			return new NumberField();
		}else if( type == "datetime" ){
			return new DateField();
		}
		else{
			return null;
		}
	}
}